import datetime

from django.core.cache import cache
from django.core.serializers.base import DeserializedObject
from django.db.models import Sum
from django.http import JsonResponse, HttpResponse, HttpRequest
from django.core.paginator import Paginator

from erp.models import Question, Choice
from erp.utils import api_data, json_serialize, json_deserialize, Cache


def question(request):
    page = request.GET.get('page', 1)
    per_page = request.GET.get('per_page', 10)
    keyword = request.GET.get('keyword', '')
    models = Question.objects.filter(question_text__icontains=keyword).values()

    pager = Paginator(models, per_page)
    model_list = list(pager.get_page(page))
    model_cache = Cache.get('model_list', model_list)
    print(model_cache, type(model_cache))
    return JsonResponse(api_data(model_list, pager=pager), safe=False)


def choice_group_qid(request):
    models = Choice.objects.values('question_id').annotate(votes=Sum('votes')).order_by('-votes')

    return JsonResponse(api_data(models), safe=False)
    # return HttpResponse(json_serialize(models), content_type='application/json')
